import { initWebGpu } from "../../utils/gputools";
import type { Base } from "../Base";
import triangleVertWGSL from "../../shaders/triangle.vert.wgsl";
import redFragWGSL from "../../shaders/red.frag.wgsl";
export default class TriangleMSAA implements Base {
  name = "TriangleMSAA";
  async run(canvas: HTMLCanvasElement) {
    const result = await initWebGpu(canvas);
    if (!result) {
      return;
    }
    const { device, context, presentationFormat } = result;


    const sampleCount = 4;
    const pipeline = device.createRenderPipeline({
      layout: "auto",
      vertex: {
        module: device.createShaderModule({
          code: triangleVertWGSL,
        }),
      },
      fragment: {
        module: device.createShaderModule({
          code: redFragWGSL,
        }),
        targets: [
          {
            format: presentationFormat,
          },
        ],
      },
      primitive: {
        topology: "triangle-list",
      },
      multisample: {
        count: sampleCount,
      },
    });

    const texture = device.createTexture({
      size: [canvas.width, canvas.height],
      sampleCount,
      format: presentationFormat,
      usage: GPUTextureUsage.RENDER_ATTACHMENT,
    });

    const view = texture.createView();

    function frame() {
      const commandEncoder = device.createCommandEncoder();
      const renderPassDescriptor: GPURenderPassDescriptor = {
        colorAttachments: [
          {
            view,
            resolveTarget: context.getCurrentTexture().createView(),
            clearValue: { r: 0, g: 0, b: 0, a: 0 },
            loadOp: "clear",
            storeOp: "discard",
          },
        ],
      };
      const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
      passEncoder.setPipeline(pipeline);
      passEncoder.draw(3);
      passEncoder.end();

      const commandBuffer = commandEncoder.finish();
      device.queue.submit([commandBuffer]);
      requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
  }
}
